package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.dto.LikesBehaviorDto;
import com.heima.behavior.dto.UnLikesBehaviorDto;
import com.heima.behavior.entity.ApLikesBehavior;
import com.heima.behavior.entity.ApUnlikesBehavior;
import com.heima.behavior.entity.UpdateArticleMessage;
import com.heima.behavior.service.ILikeService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.AppThreadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class LikeServiceImpl implements ILikeService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    KafkaTemplate<String, String> kafkaTemplate;

    /*
        保存用户点赞文章行为
     */
    @Override
    public ResponseResult saveLikes(LikesBehaviorDto dto) {
        //构建ApLikesBehavior对象
        ApLikesBehavior likesBehavior = new ApLikesBehavior();
        //获取userId
        User user = AppThreadUtil.getThread();
        if (user != null){
            likesBehavior.setUserId(user.getUserId());
        }else {
            //设备id
            likesBehavior.setEquipmentId(dto.getEquipmentId());
        }
        likesBehavior.setArticleId(dto.getArticleId());     //文章Id
        likesBehavior.setType(0);       //点赞内容
        likesBehavior.setOperation(dto.getOperation());     //用户点赞行为
        likesBehavior.setCreatedTime(new Date());       //点赞的时间

        //调用mongodb保存用户点赞行为
        //判断当前用户是否对该文章已经做过点赞行为
        Query query = new Query();
        query.addCriteria(Criteria.where("articleId").is(dto.getArticleId()));
        if (user.getUserId() != null){
            //根据用户id查询
            query.addCriteria(Criteria.where("userId").is(user.getUserId()));
        }else {
            //根据设备Id查询
            query.addCriteria(Criteria.where("equipmentId").is(dto.getEquipmentId()));
        }
        ApLikesBehavior one = mongoTemplate.findOne(query, ApLikesBehavior.class);
        //没有记录  新增
        if (one == null){
            if (dto.getOperation() == 0){
            mongoTemplate.save(likesBehavior);
            //发送到kafka
            sendMsg(dto);
            }
        }else {
            //判断用户行为是否和数据库的行为一致
            if (one.getOperation() != dto.getOperation()){
                one.setOperation(dto.getOperation());
                mongoTemplate.save(one);
                //发送到kafka
                sendMsg(dto);
            }
        }
        return ResponseResult.okResult();
    }

    /*
        查询点赞
     */
    @Override
    public ResponseResult<ApLikesBehavior> getLikes(LikesBehaviorDto dto) {
        Query query = new Query();
        query.addCriteria(Criteria.where("articleId").is(dto.getArticleId()));
        if (dto.getUserId() == null) {
            query.addCriteria(Criteria.where("equipmentId").is(dto.getEquipmentId()));
        } else {
            query.addCriteria(Criteria.where("userId").is(dto.getUserId()));
        }
        ApLikesBehavior one = mongoTemplate.findOne(query, ApLikesBehavior.class);
        return ResponseResult.okResult(one);
    }

    /*
        发送消息到kafka
     */
    private void sendMsg(LikesBehaviorDto dto) {
        UpdateArticleMessage message = new UpdateArticleMessage();
        message.setType(1);
        message.setArticleId(dto.getArticleId());
        message.setAdd(1);
        if (dto.getOperation() == 1){
            message.setAdd(-1);
        }
        String msg = JSON.toJSONString(message);
        kafkaTemplate.send(LikeTopic,msg);
    }
    @Value("${topic.like_behavior}")
    private String LikeTopic;
}
